package com.nettyBasic.bothWayChannel;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author： pang-yun
 * @date： 2021-09-14 13:17
 * 功能目的 ：用于  双向通道的服务器端
 * 实现客户端想服务端发送一个数据 后   服务端 返回一个相同的数据
 */

public class BothWayServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup(2);
        ChannelFuture channelFuture = new ServerBootstrap()
                .group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        ByteBuf buf = msg instanceof ByteBuf ? ((ByteBuf) msg) : null;
                                        String string = buf.toString(Charset.defaultCharset());
                                        System.out.println(string);
                                        ByteBuf byteBuf = ctx.alloc().buffer();
                                        byteBuf.writeBytes("hello, this is Server! input:".getBytes(StandardCharsets.UTF_8));
                                        byteBuf.writeBytes(string.getBytes(StandardCharsets.UTF_8));

                                        ctx.writeAndFlush(byteBuf);
                                    }
                                });
                            }
                        }
                ).bind(9999);
        Channel channel = channelFuture.sync().channel();
        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                bossGroup.shutdownGracefully();
                workGroup.shutdownGracefully();
            }
        });

    }
}
